﻿# -*- coding:utf-8 -*-
# file:GetWeatherandSend.py
# by QingsongLiu, 2010-09-27
# liuqs.ustc@gmail.com
"""
抓取天气预报信息，并通过pyfetion发送短信通知
"""
import os
import re
import urllib
import sys
import time
from PyFetion import *

def GetWeather(code):
	try:
		# 获取网页源文件
		sock = urllib.urlopen("http://www.weather.com.cn/html/weather/"+code+".shtml")
		strhtml = sock.read()
		#strhtml = unicode(strhtml, 'gb2312','ignore').encode('utf-8','ignore')
		# 正则式取温度信息
		strs = strhtml[strhtml.index('<div class="weatherYubao">'):strhtml.index('<div class="weatherYubao" id="weatherYubao2">')]
		strs = re.sub('<[^>]*>|\&nbsp\;|\n', '', strs)
		strs = re.sub('^\s+|高温|天气预报|低温', '', strs)
		strs = re.sub('\(|\)', ' ', strs)
		strs = re.sub('\s+', ' ', strs)
		# 获取天气描述信息
		data = re.split('\s+',strs);
		sms = data[0]+'('+data[2]+')'+data[10]+','+data[11]+data[12]+data[13]+','+data[14]+data[15]+'.';
		if re.match('08:00发布',data[2])or re.match('11:00发布',data[2]):
			sms += data[16]+data[17]+data[18]+','+data[19]+data[20]+'.'+data[21]+',';
		elif re.match('18:00发布',data[2]):
			sms += data[16]+','+data[17]+data[18]+data[19]+','+data[20]+data[21]+'.';
		sms += data[22]+data[23]+data[24]+','+data[25]+data[26]+'.';
		return sms
	except:
		return "There is sth wrong with the weather forecast"
	

def main():
	#=========================================================================
	mobile='138XXXXXXXX'#请更改为你的发送手机号码
	password='XXXXXX'#请更改为你的发送手机飞信密码
	
	#www.weather.com.cn城市代码
	citycode={'Hefei':'101220101',
		 }
	
	#sip:111111111@fetion.com.cn;p=1111 是示例的接收信息的sip号码,请将此改成实际的接收信息手机的sip号码
	#对于没有开通飞信功能的接收信息手机,可以直接以手机号码发送
	#注意:已经开通飞信功能的手机,只能以上面sip号码的方式发送.推荐以第一种方式发送.
	peoplecity=[
		     '138XXXXXXXXX-Hefei',#接收手机的号码与天气地点
		    ]
	#=========================================================================
	citymsg = {}
	try:
		phone=PyFetion(mobile,password,"TCP",debug="FILE")
		phone.login(FetionHidden)
		for ss in peoplecity:
			data=ss.split('-')
			if data[1] not in citymsg:
				citymsg[data[1]] = GetWeather(citycode[data[1]])
			#send
			phone.send_sms(citymsg[data[1]],data[0],long=True)
		phone.logout()
		print "Done."
	except:
		print "ERROR: corrent your mobile NO. and password"
		return -1
	

if __name__ == "__main__":
	sys.exit(main())
	
